﻿using System.Linq.Expressions;
using AutoMapper;
using CozeDomain.Entities;
using CozeDomain.IRepositories;
using D.Util.UtilCache;
using D.UtilCore.Dtos;
using D.UtilCore.JwtUtil;
using D.UtilFreesqlOrm;
using Microsoft.AspNetCore.Http;
using D.Util.UtilNLog;
using CozeDto.ProjectInstanceDtos;
using CozeDomain.IServices;
using CozeDto.ProjectDtos;
using CozeDto.SaleApplyForDtos;
using System.Data;
using CozeDto.AdminDtos;

namespace CozeDomain.Services
{
    /// <summary>
    /// 管理员业务实现
    /// </summary>
    public class ProjectInstanceService : BaseService<ProjectInstanceEntity>, IProjectInstanceService
    {
        private readonly IMapper _mapper;
        private readonly ICacheService _cache;
        private readonly IJwtService _tokenService;
        private readonly INLogService _nlogService;
        private readonly IProjectInstanceEntityRepository _repository;
        private readonly IProjectEntityRepository _projectEntityRepository;
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly ITenantsEntityRepository _tenantsEntityRepository;
        private readonly IMyCollectionEntityRepository _myCollectionEntityRepository;
        /// <summary>
        /// 构造注入
        /// </summary>
        public ProjectInstanceService(IMapper mapper, ICacheService cache, IJwtService tokenService, INLogService nlogService, IHttpContextAccessor httpContextAccessor,
            IProjectInstanceEntityRepository repository, IProjectEntityRepository projectEntityRepository,
            ITenantsEntityRepository tenantsEntityRepository, IMyCollectionEntityRepository myCollectionEntityRepository)
        {
            // 用于base方法
            base._baseDal = repository;
            this._repository = repository;
            _cache = cache;
            _mapper = mapper;
            _nlogService = nlogService;
            _tokenService = tokenService;
            _httpContextAccessor = httpContextAccessor;
            _projectEntityRepository = projectEntityRepository;
            _tenantsEntityRepository = tenantsEntityRepository;
            _myCollectionEntityRepository = myCollectionEntityRepository;
        }

        #region 增删改查

        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="reqModel"></param>
        /// <returns></returns>
        public async Task<ApiResult<int>> AddProjectInstanceAsync(ReqAddProjectInstance reqModel)
        {
            var insertEntities = new List<ProjectInstanceEntity>();
            foreach (var item in reqModel.ProjectIds)
            {
                insertEntities.Add(new ProjectInstanceEntity()
                {
                    DeleteFlag = false,
                    CreateTime = DateTime.Now,
                    Id = D.UtilFreesqlOrm.FreesqlOrm.NewId,
                    CreateUser = reqModel.CreateUser,
                    TenantId = reqModel.TenantId,
                    ProjectId = item,
                });
            }

            // 根据站点ID删除
            await _repository.DeleteAsync(m => m.TenantId == reqModel.TenantId);
            // 批量新增
            var dbres = await _repository.AddListAsync(insertEntities);

            return dbres.NormalResponse();
        }

        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="tenantId"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<ApiResult<RepProjectList>> QueryProjectListByTenantIdAsync(string tenantId)
        {
            // 获取站点信息
            var tenants = await _tenantsEntityRepository.GetModelAsync(m => m.Id == tenantId);
            // 获取当前站点所包含项目
            var currentTenantProjects = await _repository.GetListAsync(m => m.TenantId == tenantId);
            // 获取所有项目
            List<ProjectEntity>? allProjects = await _projectEntityRepository.GetListAsync();

            // 从所有项目去除
            var data = new List<TransferDataSource>();
            foreach (var item in allProjects)
            {
                if (currentTenantProjects.Exists(m => m.ProjectId == item.Id))
                {// 存在，则放入左侧
                    data.Add(new TransferDataSource()
                    {
                        Key = item.Id,
                        Title = item.Name,
                        Description = item.Description,
                        Selected = true
                    });
                }
                else
                {// 不存在，则放入右侧
                    data.Add(new TransferDataSource()
                    {
                        Key = item.Id,
                        Title = item.Name,
                        Description = item.Description,
                    });
                }
            }

            var res = new RepProjectList()
            {
                Name = tenants.Name,
                TenantId = tenants.Id,
                Data = data
            };

            return res.GetResponse();
        }

        /// <summary>
        /// 获取分页
        /// </summary>
        /// <param name="reqQueryProjectInstancePage"></param>
        /// <returns></returns>
        public async Task<ApiResult<PageModel<RepProjectInstanceInfo>>> QueryProjectInstancePagesAsync(ReqQueryProjectInstancePage reqQueryProjectInstancePage)
        {
            var dbres = await _repository.QueryProjectInstancePagesAsync(reqQueryProjectInstancePage);
            var res = new PageModel<RepProjectInstanceInfo>()
            {
                PageNo = reqQueryProjectInstancePage.PageNo,
                PageSize = reqQueryProjectInstancePage.PageSize,
                Data = dbres.Item2,
                TotalCount = dbres.Item1,
                TotalPage = reqQueryProjectInstancePage.PageSize > 0 ? (int)Math.Ceiling(dbres.Item1 / (double)reqQueryProjectInstancePage.PageSize) : 0
            };
            return res.GetResponse();
        }

        /// <summary>
        /// 查询列表
        /// </summary>
        /// <param name="reqQueryProjectInstanceList"></param>
        /// <returns></returns>
        public async Task<ApiResult<List<RepProjectInfo>>> QueryProjectListAsync(ReqQueryProjectInstanceList reqQueryProjectInstanceList, string userId)
        {
            var res = await _repository.QueryProjectListAsync(reqQueryProjectInstanceList);
            foreach (var item in res)
            {
                item.IsFavorite = await _myCollectionEntityRepository.ExistsAsync(m => m.ProjectId == item.Id && m.UserId == userId);
            }
            return res.GetResponse();
        }

        /// <summary>
        /// 获取单个
        /// </summary>
        /// <param name="id"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        public async Task<ApiResult<RepProjectInfo>> GetProjectAsync(string id,string userId)
        {
            var dbRes = await _projectEntityRepository.GetModelAsync(m => m.Id == id);
            var res = _mapper.Map<ProjectEntity, RepProjectInfo>(dbRes);
            if (res != null)
            {
                res.IsFavorite = await _myCollectionEntityRepository.ExistsAsync(m => m.ProjectId == id && m.UserId == userId);
            }
            return res.GetResponse();
        }
        #endregion
    }
}